Implementing do-while Loops in Java
Course: Core Java Training
Topic: Implementing do-while Loops
Course Link: Core Java Training Course
Demo Link: Register for a Course Demo
JustAcademy Homepage: Visit JustAcademy
1. Introduction to do-while Loops
The do-while loop is a repetition control statement in Java that executes a block of code first and checks the loop condition afterward. If the condition evaluates to true, the loop executes another iteration. If the condition evaluates to false, the loop terminates.
The most important characteristic of a do-while loop is that its body executes at least once, even if the condition is false at the beginning. This makes it useful for tasks such as displaying a menu, requesting user input, repeating a calculation, and asking whether a user wants to continue.
Learning objectives
- Understand the purpose and syntax of a do-while loop.
- Learn how to initialize and update loop-control variables.
- Understand the execution sequence of a do-while loop.
- Compare do-while loops with while and for loops.
- Use do-while loops for menus, input validation, and repeated calculations.
- Identify infinite loops and common programming errors.
- Practice implementing do-while loops in real-world Java programs.
2. Syntax of a do-while Loop
The basic syntax of a do-while loop is:
do {
// Statements to execute
} while (condition);
Important: The semicolon after while (condition) is required.
Components of the syntax
| Component |
Description |
do |
Begins the loop body. |
{ } |
Enclose the statements that are executed during each iteration. |
| Loop body |
Contains the instructions to execute repeatedly. |
while |
Introduces the condition that determines whether another iteration should occur. |
| Condition |
A Boolean expression that evaluates to true or false. |
; |
Terminates the complete do-while statement. |
3. How a do-while Loop Works
A do-while loop follows a straightforward execution sequence. Unlike a while loop, it does not test the condition before the first execution of the body.
- Java enters the
do block.
- The statements inside the block execute.
- The condition after the
while keyword is evaluated.
- If the condition is true, execution returns to the beginning of the do block.
- If the condition is false, the loop terminates and execution continues with the next statement.
Basic flow
Start
|
Execute loop body
|
Evaluate condition
|
+-- true --> Execute loop body again
|
+-- false --> Exit loop
4. First do-while Loop Program
The following program displays a message five times using a do-while loop.
public class DoWhileExample {
public static void main(String[] args) {
int count = 1;
do {
System.out.println("Welcome to Java");
count++;
} while (count <= 5);
}
}
Output:
Welcome to Java
Welcome to Java
Welcome to Java
Welcome to Java
Welcome to Java
Explanation:
- The variable
count starts at 1.
- The message is printed before the condition is checked.
- The statement
count++ increases count by one.
- The loop continues while count is less than or equal to 5.
- After count becomes 6, the condition is false and the loop ends.
5. Understanding Initialization, Condition, and Update
Most counter-based do-while loops use three important elements: initialization, a condition, and an update operation.
int number = 1; // Initialization
do {
System.out.println(number);
number++; // Update
} while (number <= 5); // Condition
| Element |
Purpose |
Example |
| Initialization |
Sets the starting value before the loop begins. |
int number = 1; |
| Condition |
Determines whether another iteration should occur. |
number <= 5 |
| Update |
Changes the variable to move the loop toward termination. |
number++; |
If the update is missing or does not move the variable toward the stopping condition, the loop may execute indefinitely.
6. Why Does a do-while Loop Execute at Least Once?
The do-while loop checks its condition after executing the body. Therefore, even when the condition is initially false, the first execution still occurs.
public class DoWhileOnce {
public static void main(String[] args) {
int number = 10;
do {
System.out.println("The body executed");
} while (number < 5);
}
}
Output:
The body executed
The condition number < 5 is false because number is 10. However, Java executes the body before checking the condition, so the message appears once.
7. Difference Between while and do-while Loops
Both while and do-while loops repeat statements based on a Boolean condition. Their main difference is when the condition is evaluated.
| Feature |
while loop |
do-while loop |
| Condition check |
Before the body |
After the body |
| Minimum executions |
Zero |
One |
| Semicolon after condition |
Not required as part of the loop syntax |
Required |
| Common use |
Repeat only when a condition is already true |
Perform an action at least once |
Comparison example
int value = 8;
while (value < 5) {
System.out.println("while loop");
}
do {
System.out.println("do-while loop");
} while (value < 5);
Output:
do-while loop
The while loop does not execute because its condition is false at the start. The do-while loop executes once before checking the same condition.
8. Implementing a Countdown with do-while
A countdown is a simple example of using a do-while loop with a decreasing counter.
public class Countdown {
public static void main(String[] args) {
int count = 5;
do {
System.out.println(count);
count--;
} while (count >= 1);
System.out.println("Countdown complete!");
}
}
Output:
5
4
3
2
1
Countdown complete!
The counter begins at 5 and decreases by one during each iteration. When it becomes 0, the condition is false and the loop terminates.
9. Implementing a Menu-Driven Program
Menu-driven programs frequently use do-while loops because the menu should appear at least once. The loop can continue until the user selects an exit option.
import java.util.Scanner;
public class MenuProgram {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("\\n--- Main Menu ---");
System.out.println("1. Say Hello");
System.out.println("2. Display a Message");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Hello, Java learner!");
break;
case 2:
System.out.println("Keep practicing Java.");
break;
case 3:
System.out.println("Exiting program...");
break;
default:
System.out.println("Invalid choice. Try again.");
}
} while (choice != 3);
scanner.close();
}
}
Explanation: The menu is displayed, and the program reads the user's choice. The switch statement processes that choice. The do-while loop repeats until the user enters 3.
Important: This beginner example expects numeric input. If a user enters text instead of a number, Scanner.nextInt() can throw an input mismatch exception. Robust applications should validate input and handle invalid data appropriately.
10. Implementing Input Validation
A do-while loop is useful when input must be requested at least once and checked before the program continues. For example, an application can repeatedly request a number within a permitted range.
import java.util.Scanner;
public class InputValidation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int age;
do {
System.out.print("Enter an age between 1 and 120: ");
age = scanner.nextInt();
if (age < 1 || age > 120) {
System.out.println("Invalid age. Please try again.");
}
} while (age < 1 || age > 120);
System.out.println("Accepted age: " + age);
scanner.close();
}
}
The program keeps requesting an age until the entered value falls between 1 and 120. This example validates the numeric range; production code should also handle non-numeric input.
11. Calculating the Sum of Numbers
Loops can accumulate values by adding each new number to a running total. The following example calculates the sum from 1 to 5.
public class SumUsingDoWhile {
public static void main(String[] args) {
int number = 1;
int sum = 0;
do {
sum += number;
number++;
} while (number <= 5);
System.out.println("Sum = " + sum);
}
}
Output:
Sum = 15
The variable sum stores the running total. Each iteration adds the current number and then increases the counter. The final result is 1 + 2 + 3 + 4 + 5 = 15.
12. Calculating a Factorial Using do-while
The factorial of a non-negative integer is the product of all positive integers up to that number. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120, while 0! = 1.
public class FactorialExample {
public static void main(String[] args) {
int number = 5;
int counter = 1;
long factorial = 1;
if (number < 0) {
System.out.println("Factorial is not defined for negative integers.");
} else if (number == 0) {
System.out.println("Factorial = 1");
} else {
do {
factorial *= counter;
counter++;
} while (counter <= number);
System.out.println("Factorial = " + factorial);
}
}
}
Output:
Factorial = 120
The program multiplies the running result by each integer from 1 through 5. The negative and zero cases are handled separately because the do-while body always executes at least once. For large inputs, remember that even the long type has a finite range and can overflow.
13. Using break in a do-while Loop
The break statement immediately exits the innermost loop. It can be used when a particular event should stop repetition before the loop condition becomes false.
public class BreakExample {
public static void main(String[] args) {
int number = 1;
do {
if (number == 4) {
break;
}
System.out.println(number);
number++;
} while (number <= 10);
System.out.println("Loop ended");
}
}
Output:
1
2
3
Loop ended
When number becomes 4, the break statement exits the loop immediately. The remaining statements in the body are not executed for that iteration.
14. Using continue in a do-while Loop
The continue statement skips the remaining statements in the current iteration and proceeds to the next iteration. In a do-while loop, control proceeds to the condition check before another iteration begins.
public class ContinueExample {
public static void main(String[] args) {
int number = 0;
do {
number++;
if (number == 3) {
continue;
}
System.out.println(number);
} while (number < 5);
}
}
Output:
1
2
4
5
The value 3 is skipped. Notice that the counter is incremented before continue; otherwise, the condition and update logic might cause an infinite loop.
15. Nested do-while Loops
A nested do-while loop is a do-while loop placed inside another do-while loop. Nested loops are useful for generating patterns, working with rows and columns, and processing two-dimensional data.
public class NestedDoWhile {
public static void main(String[] args) {
int row = 1;
do {
int column = 1;
do {
System.out.print("* ");
column++;
} while (column <= 3);
System.out.println();
row++;
} while (row <= 3);
}
}
Output:
* * *
* * *
* * *
The outer loop creates three rows. Each time the outer loop runs, the inner loop prints three asterisks. The inner counter is reinitialized for each row.
16. Infinite do-while Loops
An infinite loop continues without reaching a normal termination condition. In a do-while loop, this can happen if the condition remains true or if the statements never update the values needed to make it false.
Incorrect example
int number = 1;
do {
System.out.println(number);
} while (number <= 5);
The value of number remains 1, so the condition remains true indefinitely.
Corrected example
int number = 1;
do {
System.out.println(number);
number++;
} while (number <= 5);
The counter increases during each iteration, allowing the condition to become false after the value reaches 6.
17. Common Errors When Implementing do-while Loops
- Missing the final semicolon: Java requires a semicolon after
while (condition).
- Incorrect condition: A wrong comparison operator may cause the loop to repeat too many or too few times.
- Missing update: A loop-control variable may never change, creating an infinite loop.
- Incorrect initialization: An unsuitable starting value can produce unexpected results.
- Assuming the body can execute zero times: A do-while body always executes at least once unless control leaves it abruptly.
- Misusing continue: Skipping a counter update can prevent termination.
- Invalid user input: Input methods such as
nextInt() can fail when the input is not numeric.
- Integer overflow: A counter may overflow in long-running loops or when approaching the limits of its data type.
- Unclear stopping conditions: Complex conditions can make loop behavior difficult to understand and debug.
18. Best Practices for do-while Loops
- Use a do-while loop when the body must execute at least once.
- Write a clear condition that describes when repetition should continue.
- Ensure the loop changes state so it can eventually terminate.
- Use meaningful variable names such as
attempts, choice, and counter.
- Use braces to make the loop body easy to read.
- Keep the loop body focused on one understandable task.
- Validate user input when working with menus or data-entry operations.
- Use
break and continue only when they improve clarity.
- Test boundary conditions, including a condition that is initially false.
- Choose a while loop instead when the body should not execute if the initial condition is false.
19. Practice Exercises
Exercise 1: Print Numbers
Write a Java program using a do-while loop to print numbers from 1 to 10.
Exercise 2: Reverse Countdown
Create a program that prints numbers from 10 down to 1 using a do-while loop.
Exercise 3: Even Numbers
Use a do-while loop to display even numbers from 2 through 20.
Exercise 4: Sum of Digits
Write a program that calculates the sum of the digits of a positive integer using repeated division and remainder operations.
Exercise 5: Menu-Based Calculator
Build a calculator menu that performs addition, subtraction, multiplication, or division. Repeat the menu until the user selects Exit.
Exercise 6: Input Validation
Ask the user to enter a number between 1 and 100. Repeat the prompt until the entered number falls within the permitted range.
Exercise 7: Multiplication Table
Ask for a number and display its multiplication table from 1 through 10 using a do-while loop.
Exercise 8: Guessing Game
Create a simple number-guessing program that continues asking for guesses until the user enters the correct number. Consider how to handle invalid input.
20. Interview Questions and Answers
Q1. What is a do-while loop in Java?
A do-while loop is a control structure that executes a block of statements first and evaluates its Boolean continuation condition afterward.
Q2. What is the main advantage of a do-while loop?
Its body executes at least once, making it suitable for menus, prompts, and tasks that must happen before a condition is evaluated.
Q3. Is the semicolon after the while condition mandatory?
Yes. A do-while statement ends with a semicolon after the closing parenthesis of the condition.
Q4. Can a do-while loop execute only once?
Yes. If the condition is false after the first execution, the loop terminates after that single iteration.
Q5. What happens when the condition is initially false?
The loop body still executes once. The condition is checked only after the body completes normally and reaches the condition check.
Q6. What is the difference between while and do-while?
A while loop checks its condition before the body and may execute zero times. A do-while loop checks its condition afterward and executes the body at least once.
Q7. Can a do-while loop contain a break statement?
Yes. The break statement immediately exits the innermost loop in which it appears.
Q8. What does continue do in a do-while loop?
It skips the remaining statements in the current iteration and transfers control to the loop's condition check.
Q9. What causes an infinite do-while loop?
An infinite loop may occur when the condition never becomes false, often because a control variable is not updated correctly.
Q10. When should a do-while loop be used?
Use it when an operation must run at least once, such as displaying a menu or requesting an initial input before checking whether to repeat.
21. Quick Revision Checklist
- Understand the purpose and syntax of the do-while loop.
- Remember that the loop body executes before the condition is evaluated.
- Include the required semicolon after the condition.
- Initialize and update control variables correctly.
- Understand how do-while differs from while and for loops.
- Practice menu-driven programs and input validation.
- Know how break and continue affect loop execution.
- Recognize and correct infinite loops.
- Test cases where the condition is false after the first iteration.
22. Conclusion
The do-while loop is an important Java control-flow structure for repeating statements when the body must execute at least once. It is particularly useful for interactive menus, input validation, countdowns, repeated calculations, and simple games. Correct initialization, clear conditions, and appropriate update operations are essential for reliable loop behavior.
Continue your programming journey with the Core Java Training Course, register for a course demo, or visit the JustAcademy homepage.
Official Java reference: Oracle Java Tutorial: The while and do-while Statements.